import type { H3Event } from "h3";

type LoggerInst = {
  info: (msg: any, params?: any) => void;
};

const defaultLogger = {
  info: (msg: any, params?: any) => {
    console.log(msg, params);
  },
};

let logger: LoggerInst = defaultLogger;

export default function requestLogger(logLogger?: any) {
  if (logLogger) {
    logger = logLogger;
  }
  return async (e: H3Event, next: () => unknown) => {
    e.context._reqStartTime = Date.now();
    const url = new URL(e.req.url);
    e.context._reqPath = url.pathname;
    logger.info(`<-- ${e.req.method} ${url.pathname}${url.search}`);
    let raw;
    let status = 200;
    try {
      raw = await next();
    } catch (error: any) {
      raw = error;
      status = error.status || 500;
    }
    const diff = Date.now() - (e.context._reqStartTime as number);
    logger.info(
      `--> ${e.req.method} ${e.context._reqPath} ${status} ${diff}ms`,
    );
    return raw;
  };
}
